package com.mallbook.controller.servlet.front;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Orders;
import com.mallbook.model.pojo.OrdersDetails;
import com.mallbook.model.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-07
 */
@WebServlet("/alipay")
public class PayServlet extends HttpServlet {
    private Properties prop = new Properties();
    private OrderService orderService = new OrderService();
    private static final Logger logger = LoggerFactory.getLogger(PayServlet.class);

    @Override
    public void init() {
        InputStream is = PayServlet.class.getClassLoader().getResourceAsStream("alipay.properties");
        try {
            prop.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = req.getParameter("opr");
        switch (opr) {
            case "pay":
                doPay(req, resp);
                break;
            case "notify":
                doNotify(req, resp);
                break;
        }

    }

    private void doNotify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取订单ID
        String orderId = req.getParameter("out_trade_no");
        logger.info("订单ID{}", orderId);
        // 修改订单状态
        try {
            if (!orderId.isEmpty()) {
                orderService.updateOrderState(2, Integer.parseInt(orderId),null);
            }

        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("状态修改失败");
        }

        req.getRequestDispatcher("/WEB-INF/front/pay_suc.jsp").forward(req, resp);
    }

    private void doPay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=" + prop.getProperty("charset"));
        AlipayClient alipayClient = new DefaultAlipayClient(prop.getProperty("gatewayUrl"), prop.getProperty("app_id"),
                prop.getProperty("merchant_private_key"), "json", prop.getProperty("charset"),
                prop.getProperty("alipay_public_key"), prop.getProperty("sign_type"));
        int orderId = Integer.parseInt(req.getParameter("id")); // 获取订单id，查询订单信息
        Orders orders = orderService.getOrdersById(orderId);

        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(prop.getProperty("return_url"));
        alipayRequest.setNotifyUrl(prop.getProperty("notify_url"));
        String out_trade_no = String.valueOf(orderId);


        String total_amount = orders.getTotalMoney().toString();
        String subject = "MallBook";
        String body = "商品支付";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
                + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = "";
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new ServiceException("支付失败", e);
        }
        System.out.println(result);
        PrintWriter writer = resp.getWriter();
        writer.write(result);
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
